from collections import deque


class Tree(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# 广度优先
def treeToList(tree):
    if not tree:
        return []
    res = []
    q = deque()
    q.append(tree)
    while len(q) > 0:
        size = len(q)
        while size > 0:
            cur = q.popleft()
            # 将None也补齐
            if cur:
                res.append(cur.val)
                q.append(cur.left)
                q.append(cur.right)
            else:
                res.append(None)
            size -= 1
    while res[-1] == None:
        res.pop(-1)
    return res


def listToTree(list):
    if not list:
        return Tree()
    if len(list) == 1:
        return Tree(list[0])
    res = Tree(list.pop(0))
    q = deque()
    q.append(res)
    while len(q) > 0 and len(list) > 0:
        size = len(q)
        while size > 0 and len(list) > 0:
            cur = q.popleft()
            # 填入左节点的值
            if cur:
                val = list.pop(0)
                if val:
                    cur.left = Tree(val)
                else:
                    cur.left = None
                val = list.pop(0)
                if val:
                    cur.right = Tree(val)
                else:
                    cur.right = None
                q.append(cur.left)
                q.append(cur.right)
            size -= 1
    return res


tree = listToTree([1, None, 2, 3, 4, 5, 6])
print(tree.val)
print(tree.left)
print(tree.right.val)
print(tree.right.left.val)
print(tree.right.right.val)
print(treeToList(tree))
